package 我的Java学习_算法基础.day_08;

import java.util.Arrays;

/**
 * @author 挚爱之夕
 * @date 2021/8/24 - 08 - 24 - 7:50
 * @Description: 我的Java学习.day_08
 * @Version: 1.0
 */
public class _128_几个背包相关问题 {
    public static void main(String[] args) {
//        Scanner sc = new Scanner(System.in);
//        int n = sc.nextInt();
//        double weight = sc.nextDouble();
//        Commodity[] commodities = new Commodity[n];
//        for (int i = 0; i < n; i++) {
//            commodities[i] = new Commodity(sc.nextDouble(),sc.nextDouble());
//        }
        int n = 5,weight = 10;
        int[] w = {1,2,3,4,5};
        int[] v = {3,4,3,1,4};
        Commodity[] commodities = new Commodity[n];
        for (int i = 0; i < n; i++) {
            commodities[i] = new Commodity(w[i],v[i]);
        }
        Arrays.sort(commodities);
        double maxValue = maxValue(commodities,weight);
        System.out.println(maxValue);
    }
    //最优装载，weight数组是已经从小到大排好的,限制重量下，取最多数量的物品
    private static int count(int n,int[] weight,int limit){
        int sum = 0;
        int count=0;
        for (int i = 0; i < n; i++) {
            sum+=weight[i];
            if(sum>limit)
                break;
            count++;
        }
        return count;
    }
    //部分背包,取weight重的物品，单一物品可切割，求可取最大价值，commodities数组根据单价已从大到小排序
    private static double maxValue(Commodity[] commodities,double weight){
        double maxValue = 0;
        for (int i = 0; i < commodities.length; i++) {
            Commodity commodity = commodities[i];
            double w = commodity.weight;
            double v = commodity.value;
            if(w<=weight){
                maxValue+=v;
                weight-=w;
            }else {
                maxValue+=weight*commodity.getUnitPrice();
                break;
            }
        }
        return maxValue;
    }
    private static class Commodity implements Comparable<Commodity>{
        double weight;
        double value;

        public Commodity(double weight, double value) {
            this.weight = weight;
            this.value = value;
        }
        public double getUnitPrice(){
            return this.value/this.weight;
        }
        //单价从高到低排序
        @Override
        public int compareTo(Commodity o) {
             if(this.getUnitPrice()-o.getUnitPrice()==0)
                 return 0;
             else if(this.getUnitPrice()-o.getUnitPrice()<0)
                 return 1;
             else
                 return -1;
        }
    }
}
